package com.auth.manager.service.dict.impl;

import com.auth.manager.common.ex.BizException;
import com.auth.manager.mapper.dict.StandardCodeTypeMapper;
import com.auth.manager.pojo.dict.StandardCodeType;
import com.auth.manager.service.dict.StandardCodeTypeService;
import com.auth.manager.utils.DateTimeUtil;
import com.auth.manager.utils.page.PageUtil;
import com.auth.manager.utils.page.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @version 1.0.0
 * @Date: 2022/5/12 16:46
 * @Author ZhuYouBin
 * @Description 标准代码分类
 */
@Service
public class StandardCodeTypeServiceImpl extends ServiceImpl<StandardCodeTypeMapper, StandardCodeType> implements StandardCodeTypeService {

    @Override
    public void createCodeType(StandardCodeType standardCodeType) {
        // 判断分类代码是否存在
        QueryWrapper<StandardCodeType> wrapper = new QueryWrapper<>();
        wrapper.eq("code", standardCodeType.getCode());
        wrapper.last("limit 1");
        long count = this.count(wrapper);
        if (count > 0) {
            throw new BizException("分类代码已经存在");
        }

        standardCodeType.setDeleted("01");
        standardCodeType.setCreateTime(DateTimeUtil.currentDateTime());
        // 新增
        this.save(standardCodeType);
    }

    @Override
    public void removeCodeType(String id) {
        StandardCodeType codeType = this.getById(id);
        if (!Optional.ofNullable(codeType).isPresent()) {
            throw new BizException("分类不存在");
        }
        codeType.setDeleted("02");
        this.updateById(codeType);
    }

    @Override
    public void updateCodeType(StandardCodeType standardCodeType) {
        // 判断分类代码是否存在
        QueryWrapper<StandardCodeType> wrapper = new QueryWrapper<>();
        wrapper.eq("code", standardCodeType.getCode());
        wrapper.ne("id", standardCodeType.getId());
        wrapper.last("limit 1");
        long count = this.count(wrapper);
        if (count > 0) {
            throw new BizException("分类代码已经存在");
        }
        // 更新
        this.updateById(standardCodeType);
    }

    @Override
    public PageVo queryPage(PageVo pageVo, StandardCodeType standardCodeType) {
        PageUtil.start(pageVo);
        List<StandardCodeType> list = this.list();
        return PageUtil.end(list);
    }
}
